package com.learning.netease.io.nio;

import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * ClassName: NioClient
 * Description: NIO 客户端，SocketChannel
 * Date: 2021/1/10 22:33 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Slf4j
public class NioClient {

    public static void main(String[] args) throws Exception {
        // 创建连接
        try (SocketChannel socketChannel = SocketChannel.open()) {
            // 设置为非阻塞模式
            socketChannel.configureBlocking(false);
            // 绑定访问的地址与端口
            socketChannel.connect(new InetSocketAddress("127.0.0.1", 8080));
            while (!socketChannel.finishConnect()) {
                // 没连接上,则一直等待
                Thread.yield();
            }
            Scanner scanner = new Scanner(System.in);
            log.info("请输入：");
            // 发送内容
            String msg = scanner.nextLine();
            // 把发送的数据装在到 ByteBuffer
            ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
            // 写出数据也是非阻塞的，需要循环写
            while (buffer.hasRemaining()) {
                socketChannel.write(buffer);
            }
            // 读取响应
            log.info("收到服务端响应:");
            ByteBuffer requestBuffer = ByteBuffer.allocate(1024);
            // 循环读取
            while (socketChannel.isOpen() && socketChannel.read(requestBuffer) != -1) {
                // 长连接情况下,需要手动判断数据有没有读取结束 (此处做一个简单的判断: 超过0字节就认为请求结束了)
                if (requestBuffer.position() > 0) {
                    break;
                }
            }
            requestBuffer.flip();
            byte[] content = new byte[requestBuffer.limit()];
            requestBuffer.get(content);
            log.info(new String(content));
            scanner.close();
            socketChannel.close();
        }
    }

}
